package com.codebox.knowledge.rxjava.operator;

import android.widget.TextView;

import java.util.ArrayList;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;


/**
 * Scan操作符，其实是充当一个累加器（累减，累乘等）的功能
 *
 * @author 李立
 * @date 2019/1/1
 */
public class Rxjava2Scan {

    public TextView mTvLog;

    public Rxjava2Scan(TextView tvLog){
        mTvLog = tvLog;
    }

    /**
     * 乘法累计
     */
    public void testScanRule(Rule rule, TextView tvLog) {

        mTvLog.setText("");

        ArrayList<Integer> numList = new ArrayList<>();
        numList.add(100);
        numList.add(20);
        numList.add(3);
        numList.add(44);
        // Scan() without initialValue parameter.
        Observable
                .fromIterable(numList)
                //给定初始值
//                .scan(initialValue, new BiFunction<Object, Integer, Object>() { })
                .scan((integer, integer2) -> {
                    if (rule == Rule.Add) {
                        return integer + integer2;
                    } else if (rule == Rule.SUB) {
                        return integer - integer2;
                    } else if (rule == Rule.MULTI) {
                        return integer * integer2;
                    } else if (rule == Rule.DIV) {
                        return integer / integer2;
                    } else {
                        return integer + integer2;
                    }
                }).subscribe(new Consumer<Integer>() {
                                 @Override
                                 public void accept(Integer integer) throws Exception {
//                                     LogUtils.e("Rxjava2Scan:testScanMulti=" + rule + ":" + integer);
                                     tvLog.append("Rxjava2Scan:testScanMulti=" + rule + ":" + integer + "\n"+"\n");
                                 }
                             }

        );

    }

    /**
     * 加减乘除规则
     */
    public enum Rule {
        Add,
        SUB,
        MULTI,
        DIV
    }

}
